import { _decorator, Component, EventTouch, Label, Node } from 'cc';
import { autoComp, rootNode } from '../Manager/BaseManager';
import { ButtonRedefine } from './ButtonRedefine';
import { StringUtil } from '../../Util/StringUtil';
const { ccclass, property } = _decorator;

@ccclass('HoldButton')
export class HoldButton extends Component {
  @autoComp(ButtonRedefine, rootNode)
  btn: ButtonRedefine;

  press: boolean = false;
  holdTimer: NodeJS.Timeout = null;
  holdInterval: NodeJS.Timeout = null;
  protected onEnable(): void {
    this.press = false;
    this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
  }

  onTouchStart(t: EventTouch) {
    if (this.press) return;
    this.press = true;
    this.node.on(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);

    if (this.holdTimer != null) clearTimeout(this.holdTimer);
    this.holdTimer = setTimeout(() => {
      if (this.holdInterval != null) clearInterval(this.holdInterval);
      this.holdInterval = setInterval(() => this.onHoldon(t), 200);
    }, 1000);
  }

  onHoldon(t: EventTouch) {
    this.btn.clickEvents.forEach((e) => {
      e.emit([t, ...StringUtil.strSplitMore(e.customEventData, String, ',')]);
    });
  }

  onTouchEnd(t: EventTouch) {
    if (!this.press) return;
    this.press = false;
    if (this.holdTimer != null) clearTimeout(this.holdTimer);
    if (this.holdInterval != null) clearInterval(this.holdInterval);
    this.holdTimer = null;
    this.holdInterval = null;
    this.node.off(Node.EventType.TOUCH_CANCEL, this.onTouchEnd, this);
    this.node.off(Node.EventType.TOUCH_END, this.onTouchEnd, this);
  }

  protected onDisable(): void {
    this.onTouchEnd(null);
  }
}
